package org.framework.common.api.websocket.handler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.framework.common.api.entity.CommonMessage;
import org.framework.common.api.service.bo.CommonMessageBo;
import org.framework.common.ext.util.datasource.DynamicDataSourceHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

/**
 * Websocket监听器
 * <p>描述: </p>
 * <p>Company: Professional</p>
 * @author chanlong(陈龙)
 * @date 2016年5月16日 下午12:54:36
 * @version 1.0.2016
 */
@Component("notify")
public class WebsocketEndNotify implements WebSocketHandler {

	private static final List<WebSocketSession> sessions;
	
	static {
		sessions = new ArrayList<WebSocketSession>();
	}
	
	@Autowired
	private CommonMessageBo bo;
	
	@Autowired
	private ThreadPoolTaskExecutor executor; 
	
	/**
	 * 
	 * @see org.springframework.web.socket.handler.AbstractWebSocketHandler#afterConnectionEstablished(org.springframework.web.socket.WebSocketSession)
	 * @author chanlong(陈龙)
	 * @date 2016年5月16日 下午5:35:38
	 */
	@Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 保存socket会话
		sessions.add(session);
        
		// 注册数据源
		DynamicDataSourceHolder.setDataSource("default");
		
		// 启动线程
		executor.execute(new Runnable() {
			@Override
			public void run() {
		        CommonMessage message;
		        
				try {
					// 读取未读消息
					message = bo.unreader();
					
					// 发送未读消息
			        String text = message.getTextMessage();
			        if(text != null){
			            session.sendMessage(new TextMessage(text));
			        }
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
    }
	
	/**
	 * 
	 * @see org.springframework.web.socket.handler.AbstractWebSocketHandler#handleTransportError(org.springframework.web.socket.WebSocketSession, java.lang.Throwable)
	 * @author chanlong(陈龙)
	 * @date 2016年5月16日 下午5:35:24
	 */
	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		if(sessions != null && session.isOpen()) {
			session.close();
			sessions.remove(session);
		}
	}

	/**
	 * 
	 * @see org.springframework.web.socket.handler.AbstractWebSocketHandler#afterConnectionClosed(org.springframework.web.socket.WebSocketSession, org.springframework.web.socket.CloseStatus)
	 * @author chanlong(陈龙)
	 * @date 2016年5月16日 下午5:35:30
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		if(sessions != null){
			session.close();
			sessions.remove(session);
		}
	}

	/**
	 * 发送消息通知.
	 * @param message
	 * @throws IOException
	 * @author chanlong(陈龙)
	 * @date 2016年5月16日 下午7:35:58
	 */
	public void sendMessage(final String message) throws IOException{
		for (WebSocketSession session : sessions) {
			TextMessage text = new TextMessage(message);
			session.sendMessage(text);
		}
	}

	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}
	
}
